<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
        :filter-btn="filterInfo.btn"
      >
        <template v-slot:filter-operateTime>
          <el-date-picker
            v-model="operateTime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            :picker-options="$fn.pickerOptionsFn()"
            align="right"
            start-placeholder="操作时间开始日期"
            end-placeholder="操作时间结束日期"
            :shortcuts="$fn.pickerOptionsFn()"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59),
            ]"
            @change="timeChange"
          ></el-date-picker>
        </template>
        <template v-slot:filter-fiscalPeriodName>
          <el-input
            v-model="filterInfo.query.fiscalPeriodName"
            class="not-mongolia"
            type="input"
            :required="true"
            :disabled="true"
            :placeholder="'请选择会计期间'"
          >
            <template #append>
              <el-icon @click="checkFinance"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </NewPageFilter>
    </div>
    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList"></NewPageFilter>
    </div>
    <!-- 表格 -->
    <TableContainer
      v-model:data="tableInfo.data"
      :tab-index="false"
      :field-list="tableInfo.fieldList"
      :handle="tableInfo.handle"
      summary="true"
      :summary-field-list="tableInfo.summaryFieldList"
      :pager="false"
      :checkBox="false"
    />
    <SelectFiscalPeriod
      v-if="selectFiscalInfo.visible"
      v-model:show-dialog="selectFiscalInfo.visible"
      :query="selectFiscalInfo.query"
      :save-empty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="callBackselectFinanceType"
    />
  </div>
</template>

<script setup name="financeStatisticalReport">
import {
  subInventorySummaryQuery,
  subInventorySummaryQueryExcel,
  subInventorySummaryQueryPrint,
} from "@/api/dataQuery";
import { fatchTemplateByCode } from '@/api/base'
import {
  getDepotAll,
  getCategoryLevelInfo,
  getDeptLevelInfo,
} from "@/api/core";
const { proxy } = getCurrentInstance();
const operateTime = ref([]);
// 过滤相关配置
const filterInfo = ref({
  query: {
    startDate: "",
    endDate: "",
    fiscalPeriodName: "",
    categoryLevel: 1,
    deptLevel: 1,
  },
  copyQuery: {},
  list: [
    {
      slot: true,
      label: "起止日期",
      value: "operateTime",
    },
    {
      label: "会计期间",
      value: "fiscalPeriodName",
      slot: true,
    },
    {
      componentType: "input",
      label: "产品分类",
      value: "categoryLevel",
      api: getCategoryLevelInfo,
      componentType: "slip-select",
      keyField: "levelName",
      valueField: "levelNum",
      event: search,
      // defaultValue: true,
    },
    {
      componentType: "input",
      label: "部门分级",
      value: "deptLevel",
      componentType: "slip-select",
      api: getDeptLevelInfo,
      keyField: "levelName",
      valueField: "levelNum",
      event: search,
      // defaultValue: true,
    },
    {
      label: "仓库",
      value: "depotId",
      componentType: "slip-select",
      query: {
        depotAuth: "id",
      },
      api: getDepotAll,
      event: search,
    },
  ],
  btn: [
    { type: "button", label: "搜索", event: search },
    { type: "button", label: "重置", event: clearSearch },
  ],
  btnList: [
    {
      type: "button",
      label: "导出excel",
      event: exportExcel,
      show: proxy.$permission("financeStatisticalReport:exportExcel"),
    },
    {
      type: "button",
      label: "打印",
      event: print,
      show: proxy.$permission("financeStatisticalReport:print"),
    },
  ],
});
// 表格相关
const tableInfo = ref({
  data: [],
  fieldList: [
    // { label: "物资分类编码", value: "productCategoryCode" },
    { label: "物资分类名称", value: "productCategoryName" },
    { label: "期初金额", value: "beginAmount" },
    { label: "采购入库", value: "purchaseReceipt" },
    { label: "盘盈入库", value: "gainReceipt" },
    { label: "采购退货", value: "purchaseReturn" },
    { label: "移入库", value: "transferReceipt" },
    { label: "领用入库", value: "collectReceipt" },
    { label: "捐赠入库", value: "donationReceipt" },
    { label: "本期增加合计金额", value: "sumIncreaseAmount" },
    { label: "科室领用", value: "deptCollect" },
    { label: "盘亏出库", value: "lossIssue" },
    { label: "报废出库", value: "scrapIssue" },
    { label: "移出库", value: "transferIssue" },
    { label: "科室退库", value: "deptReturn" },
    { label: "消耗出库", value: "consumeIssue" },
    { label: "消耗撤回", value: "consumeRevokeIssue" },
    { label: "捐赠出库", value: "donationIssue" },
    { label: "本期减少合计金额", value: "sumReduceAmount" },
    { label: "期末结存", value: "endAmount" },
  ],
  copyFieldList: [],
  summaryFieldList:[
    {value: 'beginAmount'},
    {value: 'purchaseReceipt'},
    {value: 'gainReceipt'},
    {value: 'purchaseReturn'},
    {value: 'transferReceipt'},
    {value: 'collectReceipt'},
    {value: 'donationReceipt'},
    {value: 'sumIncreaseAmount'},
    {value: 'deptCollect'},
    {value: 'lossIssue'},
    {value: 'scrapIssue'},
    {value: 'transferIssue'},
    {value: 'deptReturn'},
    {value: 'consumeIssue'},
    {value: 'consumeRevokeIssue'},
    {value: 'donationIssue'},
    {value: 'sumReduceAmount'},
    {value: 'endAmount'},
  ]
});

const selectFiscalInfo = ref({
  visible: false,
  query: { fiscalType: 1 },
});

onMounted(() => {
  filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query);
  tableInfo.value.copyFieldList = proxy.$fn.deepClone(
    tableInfo.value.fieldList
  );
});

function exportExcelList() {
  let params = {
    ...filterInfo.value.query
  };
  subInventorySummaryQueryExcel(params).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res);
    }
  });
}
function checkFinance() {
  selectFiscalInfo.value.visible = true;
}
function callBackselectFinanceType(data) {
  if (data && data.id) {
    operateTime.value = ''
    filterInfo.value.query.startDate = ''
    filterInfo.value.query.endDate = ''
    filterInfo.value.query.fiscalPeriodName = data.name;
  } else {
    filterInfo.value.query.fiscalPeriodName = "";
  }
  search();
}
function spanMethod({ row, column, rowIndex, columnIndex }) {
  let keys = ["deptClass"];
  // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
  return proxy.$fn.spanMethod(
    tableInfo.value.data,
    keys,
    rowIndex,
    columnIndex
  );
}
// 获取列表
function getList() {
  subInventorySummaryQuery(filterInfo.value.query).then((res) => {
    if(res && res.success) {
      tableInfo.value.data = res.data
    }
  });
}
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery);
  operateTime.value = [];
  tableInfo.value.data = []
}
//打印
function print() {
  if (
    !filterInfo.value.query.fiscalPeriodName &&
    !filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: '请选择会计区间或操作时间',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  } else if (
    filterInfo.value.query.fiscalPeriodName &&
    filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: '会计区间或操作时间只能同时选一个',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  fatchTemplateByCode({
    resourceCode: 'financeStatisticalReport:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp)
    }
  })
}
function getPrintData(temp) {
  subInventorySummaryQueryPrint(filterInfo.value.query).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
// 搜索
function search() {
  if (
    !filterInfo.value.query.fiscalPeriodName &&
    !filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "请选择会计区间或操作时间",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  } else if (
    filterInfo.value.query.fiscalPeriodName &&
    filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "会计区间或操作时间只能同时选一个",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  }
  getList();
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.fiscalPeriodName = ''
    filterInfo.value.query.startDate = val[0];
    filterInfo.value.query.endDate = val[1];
  } else {
    filterInfo.value.query.startDate = "";
    filterInfo.value.query.endDate = "";
  }
  search();
}
function exportExcel() {
  if (
    !filterInfo.value.query.fiscalPeriodName &&
    !filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: '请选择会计区间或操作时间',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  } else if (
    filterInfo.value.query.fiscalPeriodName &&
    filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: '会计区间或操作时间只能同时选一个',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  exportExcelList()
}
</script>

<style scoped></style>
